package com.example.petshopping.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Toast;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import androidx.core.widget.NestedScrollView;

import com.example.chongwushangcheng.adapter.CarouselAdapter;
import com.example.chongwushangcheng.enums.PetSpecialPerformanceStatusEnum;
import com.example.petshopping.R;
import com.example.petshopping.adapter.SpecialPerformanceAdapter;
import com.example.petshopping.model.Product;
import com.example.petshopping.model.SpecialPerformanceItem;
import com.example.petshopping.model.AppPetSpecialPerformanceRespVO;
import com.example.petshopping.model.AppPetSpecialPerformancePageReqVO;
import com.example.petshopping.model.CommonResult;
import com.example.petshopping.model.PageResult;
import com.example.petshopping.model.SpecialPerformanceTagVO;
import com.example.petshopping.network.RetrofitClient;
import com.example.petshopping.ui.aquarium.AquariumActivity;
import com.example.petshopping.ui.category.CategoryActivity;
import com.example.petshopping.ui.fixedprice.FixedPriceActivity;
import com.example.petshopping.ui.pet.PetActivity;
import com.example.petshopping.ui.subscribe.SubscribeActivity;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;
import com.google.android.material.tabs.TabLayout;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    private RecyclerView productList;
    private final List<SpecialPerformanceItem> specialItems = new ArrayList<>();
    private SpecialPerformanceAdapter specialAdapter;
    private int currentPage = 1;
    private static final int PAGE_SIZE = 10;
    private boolean isLoading = false;
    private boolean hasMoreData = true;
    private View loadingMoreContainer;
    private View noMoreDataHint;
    private View loadFailedHint;

    // 轮播
    private ViewPager2 carouselViewPager;
    private CarouselAdapter carouselAdapter;
    private LinearLayout indicatorContainer;
    private List<Integer> carouselImages;
    private Handler carouselHandler;
    private Runnable carouselRunnable;
    private int currentCarouselPosition = 0;

    // 标签相关
    private ChipGroup tagsWrapper;
    private final List<SpecialPerformanceTagVO> tagList = new ArrayList<>();
    private final List<Long> selectedTagIds = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 状态栏占位高度
        int resId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resId > 0) {
            int h = getResources().getDimensionPixelSize(resId);
            findViewById(R.id.status_bar_bg).getLayoutParams().height = h;
        }
        
        findViews(); // 初始化视图
        initCarousel(); // 初始化轮播
        setupSpecialPerformanceList(); // 初始化专场列表
        setupScrollToLoadMore(); // 下拉到底加载更多
        setupNavigation(); // 设置导航标签的点击监听
        setupClicks(); // 设置点击监听
        loadSpecialPerformanceTags(); // 加载宠物专场标签
    }

    private void findViews() {
        productList = findViewById(R.id.product_list);
        carouselViewPager = findViewById(R.id.carousel_viewpager);
        indicatorContainer = findViewById(R.id.indicator_container);
        loadingMoreContainer = findViewById(R.id.loading_more_container);
        noMoreDataHint = findViewById(R.id.no_more_data_hint);
        loadFailedHint = findViewById(R.id.load_failed_hint);
        tagsWrapper = findViewById(R.id.tags_wrapper);
    }

    private void setupSpecialPerformanceList() {
        if (productList == null) return;
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        productList.setLayoutManager(gridLayoutManager);

        specialAdapter = new SpecialPerformanceAdapter(this, specialItems);
        productList.setAdapter(specialAdapter);

        specialAdapter.setOnItemClickListener(new SpecialPerformanceAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(SpecialPerformanceItem item, int position) {
                Intent intent = new Intent(MainActivity.this, com.example.petshopping.ui.SpecialPerformanceActivity.class);
                intent.putExtra("special_id", item.getId());
                intent.putExtra("special_title", item.getTitle());
                startActivity(intent);
                overridePendingTransition(0, 0);
            }

            @Override
            public void onDeleteClick(SpecialPerformanceItem item, int position) {
                // 可根据需要实现删除逻辑
            }
        });

        productList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dy <= 0) return;
                int lastVisible = gridLayoutManager.findLastVisibleItemPosition();
                if (!isLoading && hasMoreData && lastVisible >= Math.max(0, specialAdapter.getItemCount() - 4)) {
                    loadMoreSpecialPerformances();
                }
            }
        });

        loadSpecialPerformances(true);
    }

    private void setupScrollToLoadMore() {
        NestedScrollView scrollView = findViewById(R.id.nested_scroll_view);
        if (scrollView != null) {
            scrollView.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
                if (!isLoading && hasMoreData && scrollY > oldScrollY) {
                    if (scrollY + v.getHeight() >= v.getChildAt(0).getMeasuredHeight() - 100) {
                        loadMoreSpecialPerformances();
                    }
                }
            });
        }
    }

    private void loadSpecialPerformances(boolean refresh) { 
        loadSpecialPerformances(refresh, false, null); 
    }

    private void loadSpecialPerformances(boolean refresh, boolean fromLoadMore) {
        loadSpecialPerformances(refresh, fromLoadMore, null);
    }

    private void loadSpecialPerformances(boolean refresh, boolean fromLoadMore, List<Long> tagIds) {
        if (isLoading) return;
        if (refresh) {
            currentPage = 1;
            hasMoreData = true;
            hideLoadingMore();
            hideNoMoreDataHint();
            hideLoadFailedHint();
        }
        isLoading = true;
        if (fromLoadMore) {
            showLoadingMore();
        }

        AppPetSpecialPerformancePageReqVO pageReqVO = new AppPetSpecialPerformancePageReqVO(
                currentPage, 
                PAGE_SIZE, 
                PetSpecialPerformanceStatusEnum.IN_PROGRESS.getCode(), 
                tagIds
        );
        
        Call<CommonResult<PageResult<AppPetSpecialPerformanceRespVO>>> call = RetrofitClient.getInstance()
                .getApiService()
                .getPetSpecialPerformancePage(pageReqVO);

        call.enqueue(new Callback<CommonResult<PageResult<AppPetSpecialPerformanceRespVO>>>() {
            @Override
            public void onResponse(Call<CommonResult<PageResult<AppPetSpecialPerformanceRespVO>>> call,
                                   Response<CommonResult<PageResult<AppPetSpecialPerformanceRespVO>>> response) {
                try {
                    if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                        PageResult<AppPetSpecialPerformanceRespVO> page = response.body().getData();
                        List<AppPetSpecialPerformanceRespVO> list = page != null ? page.getList() : null;
                        if (refresh) specialItems.clear();
                        if (list != null && !list.isEmpty()) {
                            int start = specialItems.size();
                            for (AppPetSpecialPerformanceRespVO vo : list) {
                                SpecialPerformanceItem item = new SpecialPerformanceItem(
                                        vo.getId() == null ? null : String.valueOf(vo.getId()),
                                        vo.getName(),
                                        vo.getPicUrl(),
                                        formatEndTime(vo.getEndTime()),
                                        true,
                                        vo.getCount()
                                );
                                specialItems.add(item);
                            }
                            if (refresh) {
                                specialAdapter.notifyDataSetChanged();
                            } else {
                                specialAdapter.notifyItemRangeInserted(start, list.size());
                            }

                            hasMoreData = list.size() >= PAGE_SIZE && (page.getTotal() == null || specialItems.size() < page.getTotal());
                            hideLoadFailedHint();
                            if (!hasMoreData) {
                                showNoMoreDataHint();
                            }
                        } else {
                            hasMoreData = false;
                            if (fromLoadMore) {
                                showNoMoreDataHint();
                            } else {
                                showLoadFailedHint();
                            }
                        }
                    } else {
                        hasMoreData = false;
                        if (fromLoadMore) {
                            currentPage--; // 回退页码
                        }
                        showLoadFailedHint();
                    }
                } catch (Exception e) {
                    hasMoreData = false;
                    if (fromLoadMore) {
                        currentPage--;
                    }
                    showLoadFailedHint();
                } finally {
                    isLoading = false;
                    if (fromLoadMore) hideLoadingMore();
                }
            }

            @Override
            public void onFailure(Call<CommonResult<PageResult<AppPetSpecialPerformanceRespVO>>> call, Throwable t) {
                isLoading = false;
                hasMoreData = false;
                if (fromLoadMore) {
                    currentPage--;
                    hideLoadingMore();
                }
                showLoadFailedHint();
            }
        });
    }

    private void loadMoreSpecialPerformances() {
        if (isLoading || !hasMoreData) return;
        currentPage++;
        loadSpecialPerformances(false, true);
    }

    private void showLoadingMore() {
        if (loadingMoreContainer != null) {
            loadingMoreContainer.setVisibility(View.VISIBLE);
        }
        if (noMoreDataHint != null) {
            noMoreDataHint.setVisibility(View.GONE);
        }
    }

    private void hideLoadingMore() {
        if (loadingMoreContainer != null) {
            loadingMoreContainer.setVisibility(View.GONE);
        }
    }

    private void showNoMoreDataHint() {
        if (noMoreDataHint != null) {
            noMoreDataHint.setVisibility(View.VISIBLE);
        }
        if (loadingMoreContainer != null) {
            loadingMoreContainer.setVisibility(View.GONE);
        }
        if (loadFailedHint != null) {
            loadFailedHint.setVisibility(View.GONE);
        }
    }

    private void hideNoMoreDataHint() {
        if (noMoreDataHint != null) {
            noMoreDataHint.setVisibility(View.GONE);
        }
    }

    private void showLoadFailedHint() {
        if (loadFailedHint != null) {
            loadFailedHint.setVisibility(View.VISIBLE);
        }
        if (loadingMoreContainer != null) {
            loadingMoreContainer.setVisibility(View.GONE);
        }
        if (noMoreDataHint != null) {
            noMoreDataHint.setVisibility(View.GONE);
        }
    }

    private void hideLoadFailedHint() {
        if (loadFailedHint != null) {
            loadFailedHint.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        startCarouselAutoPlay();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopCarouselAutoPlay();
    }

    private void initCarousel() {
        carouselImages = Arrays.asList(
                R.drawable.yugang,
                R.drawable.cat,
                R.drawable.canyu
        );
        carouselAdapter = new CarouselAdapter(this, carouselImages, true);
        carouselViewPager.setAdapter(carouselAdapter);
        setupCarouselIndicators();
        carouselViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                currentCarouselPosition = position;
                updateIndicators(position);
            }
        });
    }

    private void setupCarouselIndicators() {
        indicatorContainer.removeAllViews();
        for (int i = 0; i < carouselImages.size(); i++) {
            ImageView indicator = new ImageView(this);
            LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );
            p.setMargins(8, 0, 8, 0);
            indicator.setLayoutParams(p);
            indicator.setBackground(buildDot(i == 0));
            indicatorContainer.addView(indicator);
        }
    }

    private android.graphics.drawable.GradientDrawable buildDot(boolean active) {
        android.graphics.drawable.GradientDrawable d = new android.graphics.drawable.GradientDrawable();
        d.setShape(android.graphics.drawable.GradientDrawable.OVAL);
        d.setSize(16, 16);
        d.setColor(getResources().getColor(active ? android.R.color.white : android.R.color.darker_gray));
        return d;
    }

    private void updateIndicators(int position) {
        for (int i = 0; i < indicatorContainer.getChildCount(); i++) {
            indicatorContainer.getChildAt(i).setBackground(buildDot(i == position));
        }
    }

    private void startCarouselAutoPlay() {
        if (carouselHandler == null) carouselHandler = new Handler();
        if (carouselRunnable == null) {
            carouselRunnable = () -> {
                if (carouselImages != null && carouselImages.size() > 1) {
                    currentCarouselPosition = (currentCarouselPosition + 1) % carouselImages.size();
                    carouselViewPager.setCurrentItem(currentCarouselPosition, true);
                    carouselHandler.postDelayed(carouselRunnable, 3000);
                }
            };
        }
        carouselHandler.postDelayed(carouselRunnable, 3000);
    }

    private void stopCarouselAutoPlay() {
        if (carouselHandler != null && carouselRunnable != null) {
            carouselHandler.removeCallbacks(carouselRunnable);
        }
    }

    private void setupClicks() {
        findViewById(R.id.search_input).setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, com.example.petshopping.ui.search.SearchActivity.class));
            overridePendingTransition(0, 0);
        });

        Chip addTagBtn = findViewById(R.id.add_tag_btn);
        if (addTagBtn != null) {
            addTagBtn.setOnClickListener(v -> startActivity(new Intent(MainActivity.this, SubscribeActivity.class)));
        }

        setupBottomNav();
    }

    private void setupBottomNav() {
        com.google.android.material.bottomnavigation.BottomNavigationView bottomNav = findViewById(R.id.bottom_nav);
        bottomNav.setOnNavigationItemSelectedListener(item -> {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    return true;
                case R.id.navigation_category:
                    startActivity(new Intent(MainActivity.this, CategoryActivity.class));
                    overridePendingTransition(0, 0);
                    return true;
                case R.id.navigation_message:
                    startActivity(new Intent(this, com.example.petshopping.ui.message.MessageActivity.class));
                    overridePendingTransition(0, 0);
                    finish();
                    return true;
                case R.id.navigation_profile:
                    startActivity(new Intent(this, com.example.petshopping.ui.profile.ProfileActivity.class));
                    overridePendingTransition(0, 0);
                    finish();
                    return true;
            }
            return false;
        });
    }

    private void setupNavigation() {
        TabLayout navMenu = findViewById(R.id.nav_menu);
        navMenu.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                if (position != 0) {
                    switch (position) {
                        case 1:
                            startActivity(new Intent(MainActivity.this, PetActivity.class));
                            overridePendingTransition(0, 0);
                            finish();
                            break;
                        case 2:
                            startActivity(new Intent(MainActivity.this, AquariumActivity.class));
                            overridePendingTransition(0, 0);
                            finish();
                            break;
                        case 3:
                            startActivity(new Intent(MainActivity.this, FixedPriceActivity.class));
                            overridePendingTransition(0, 0);
                            finish();
                            break;
                        case 4:
                            startActivity(new Intent(MainActivity.this, com.example.petshopping.ui.samecity.SameCityActivity.class));
                            overridePendingTransition(0, 0);
                            finish();
                            break;
                    }
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) { }

            @Override
            public void onTabReselected(TabLayout.Tab tab) { }
        });
        navMenu.getTabAt(0).select();
    }


    // 时间格式化
    private String formatEndTime(LocalDateTime endTime) {
        if (endTime == null) return "时间未定";
        try {
            // 获取当前时间（加上8小时时区偏移）
            LocalDateTime now = LocalDateTime.now().plusHours(8);
            // 计算实际结束时间
            LocalDateTime actualEndTime = endTime.plusHours(8);

            // 如果当前时间已经超过了结束时间，返回"已截拍"
            if (now.isAfter(actualEndTime)) {
                return "已截拍";
            }
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd HH:mm 截拍");
            return actualEndTime.format(formatter);
        } catch (Exception e) {
            return "时间格式错误";
        }
    }

    /**
     * 加载宠物专场标签
     */
    private void loadSpecialPerformanceTags() {
        Call<CommonResult<List<SpecialPerformanceTagVO>>> call = RetrofitClient.getInstance()
                .getApiService()
                .getSpecialPerformanceTags();

        call.enqueue(new Callback<CommonResult<List<SpecialPerformanceTagVO>>>() {
            @Override
            public void onResponse(Call<CommonResult<List<SpecialPerformanceTagVO>>> call,
                                   Response<CommonResult<List<SpecialPerformanceTagVO>>> response) {
                try {
                    if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                        List<SpecialPerformanceTagVO> tags = response.body().getData();
                        if (tags != null && !tags.isEmpty()) {
                            tagList.clear();
                            tagList.addAll(tags);
                            updateTagsUI();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<CommonResult<List<SpecialPerformanceTagVO>>> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    /**
     * 更新标签UI
     */
    private void updateTagsUI() {
        if (tagsWrapper == null) return;
        
        // 清除现有的标签（保留"自定义"按钮）
        int childCount = tagsWrapper.getChildCount();
        for (int i = childCount - 1; i >= 0; i--) {
            Chip chip = (Chip) tagsWrapper.getChildAt(i);
            if (chip.getId() != R.id.add_tag_btn) {
                tagsWrapper.removeView(chip);
            }
        }

        // 添加新的标签
        for (SpecialPerformanceTagVO tag : tagList) {
            Chip chip = new Chip(this);
            chip.setText(tag.getLabel());
            chip.setCheckable(true);
            chip.setCheckedIconVisible(false);
            chip.setChipCornerRadius(20);
            
            // 设置默认样式（白色背景，紫色边框和文字）
            chip.setChipBackgroundColorResource(android.R.color.white);
            chip.setChipStrokeColorResource(R.color.colorPrimary);
            chip.setChipStrokeWidth(1.5f);
            chip.setTextColor(getResources().getColor(R.color.colorPrimary));
            
            // 设置点击监听器
            chip.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    selectedTagIds.add(tag.getId());
                    // 选中状态：紫色背景，白色文字
                    chip.setChipBackgroundColorResource(R.color.colorPrimary);
                    chip.setTextColor(getResources().getColor(android.R.color.white));
                } else {
                    selectedTagIds.remove(tag.getId());
                    // 未选中状态：白色背景，紫色边框和文字
                    chip.setChipBackgroundColorResource(android.R.color.white);
                    chip.setTextColor(getResources().getColor(R.color.colorPrimary));
                }
                // 这里可以根据选中的标签ID进行搜索
                performSearchWithTags();
            });
            
            // 在"自定义"按钮之前插入标签
            tagsWrapper.addView(chip, tagsWrapper.getChildCount() - 1);
        }
    }

    /**
     * 根据选中的标签进行搜索
     */
    private void performSearchWithTags() {
        // 重新加载专场列表，传入选中的标签ID
        if (!selectedTagIds.isEmpty()) {
            // 打印选中的标签ID（用于调试）
            StringBuilder sb = new StringBuilder("选中的标签ID: ");
            for (Long id : selectedTagIds) {
                sb.append(id).append(", ");
            }
            Toast.makeText(this, sb.toString(), Toast.LENGTH_SHORT).show();
            
            // 重新加载专场列表，传入选中的标签ID
            loadSpecialPerformances(true, false, selectedTagIds);
        } else {
            // 如果没有选中标签，加载所有专场
            loadSpecialPerformances(true, false, null);
        }
    }
}


